package com.whsr.readservice.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whsr.readservice.dao.ArticleMapper;
import com.whsr.readservice.dao.ChapterContentMapper;
import com.whsr.readservice.dao.ChapterMapper;
import com.whsr.readservice.dto.ChapterContentRequest;
import com.whsr.readservice.enums.DownBookEnum;
import com.whsr.readservice.util.HttpClientUtils;
import com.whsr.readservice.util.InterfaceUtil;
import com.whsr.readservice.util.ResultUtil;
import com.whsr.readservice.vo.Article;
import com.whsr.readservice.vo.Chapter;
import com.whsr.readservice.vo.ChapterContent;
import com.whsr.readservice.vo.JobBatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChapterContentService {

    @Autowired
    private ChapterContentMapper chapterContentMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private DownBookMaintainService downBookMaintainService;


    public JobBatch inserChapterContents(JobBatch jobBatch){
        List<Integer> bookIds = downBookMaintainService.getBookIdsBystatus(DownBookEnum.WAIT_CONTENT.getCode());
        Map<String, Object> param = new HashMap<>();
        List<Integer> updatebookIds = new ArrayList<>();
        Integer complateNum = 0;
        Integer failNum = 0;
        for (Integer bookId: bookIds) {
            List<Chapter> chapters = chapterMapper.selectChaptersNoContentByBookId(bookId);
            boolean success = true;
            if(chapters != null && chapters.size() > 0){
                for (Chapter chapter: chapters) {
                    ChapterContent chapterContent = new ChapterContent();
                    param.put("bk_id", bookId);
                    param.put("ch_id", chapter.getChId());
                    JSONObject json = HttpClientUtils.httpPost(InterfaceUtil.urls[2], param);
                    if(json == null || json.getInteger("code") != 1){
                        failNum++;
                        success = false;
                        continue;
                    }
                    String content = json.getString("ch_content");
                    try {
                        content = URLDecoder.decode(content, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        failNum++;
                        success = false;
                        continue;
                    }
                    chapterContent.setChId(chapter.getChId());
                    chapterContent.setChContent(content);
                    chapterContent.setBookId(bookId);
                    try {
                        chapterContentMapper.insertChapterContent(chapterContent);
                        complateNum++;
                    } catch (Exception e) {
                        failNum++;
                        success = false;
                        continue;
                    }
                }
            }
            if(success){
                updatebookIds.add(bookId);
            }

        }
        if(updatebookIds.size() > 0){
            int forNum = (updatebookIds.size() % InterfaceUtil.MAX_COUNT) > 0 ? (updatebookIds.size() / InterfaceUtil.MAX_COUNT) + 1 : (updatebookIds.size() / InterfaceUtil.MAX_COUNT);
            for (int i = 0; i < forNum; i++){
                List<Integer> newUpdatebookIds = null;
                if(i != forNum -1){
                    newUpdatebookIds = updatebookIds.subList(i*InterfaceUtil.MAX_COUNT, (i+1)*InterfaceUtil.MAX_COUNT);
                } else {
                    newUpdatebookIds = updatebookIds.subList(i*InterfaceUtil.MAX_COUNT, updatebookIds.size());
                }
                if(newUpdatebookIds != null && newUpdatebookIds.size() > 0){
                    try{
                        downBookMaintainService.updateDownBookMaintains(newUpdatebookIds, DownBookEnum.COMPLETE.getCode());
                    } catch (Exception e){
                        continue;
                    }
                }
            }
        }
        jobBatch.setCompleteConArtNum(updatebookIds.size());
        jobBatch.setFailConArtNum(bookIds.size() - updatebookIds.size());
        jobBatch.setCompleteConNum(complateNum);
        jobBatch.setFailConNum(failNum);
        return jobBatch;
    }

    public int insertChapters2(List<String> bookIds) {
        Map<String, Object> param = new HashMap<>();
        List<ChapterContent> chapterContents = new ArrayList<>();
        List<Chapter> chapters = chapterService.getChaptersByNotContent();
        int num = 0;
        for (Chapter chapter: chapters) {
            ChapterContent chapterContent = new ChapterContent();
            param.put("bk_id", chapter.getBookId());
            param.put("ch_id", chapter.getChId());
            JSONObject json = HttpClientUtils.httpPost(InterfaceUtil.urls[2], param);
            if(json == null || json.getInteger("code") != 1){
                continue;
            }
            String content = json.getString("ch_content");
            try {
                content = URLDecoder.decode(content, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                continue;
            }
            chapterContent.setChId(chapter.getChId());
            chapterContent.setChContent(content);
            chapterContent.setBookId(chapter.getBookId());
            chapterContents.add(chapterContent);
            if(chapterContents.size() >= 1){
                try{
                    chapterContentMapper.insertChapterContents(chapterContents);
                    num++;
                    chapterContents.clear();
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

            }
        }
        if(chapterContents.size() > 0) {
            try {
                chapterContentMapper.insertChapterContents(chapterContents);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return num * InterfaceUtil.MAX_COUNT + chapterContents.size();
    }

    public Map<String,Object> getContentByBookIdAndChId(Integer bookId, Integer chId) {
        Map<String, Object> root = new HashMap<>();
        ChapterContentRequest chapterContent = chapterContentMapper.selectContentByBookIdAndChIdOrNoChId(bookId,chId);
        chId = chapterContent.getChId();

        ChapterContentRequest chapterContentNull = new ChapterContentRequest(0,0, "",0);
        root.put("ChpterInfo", chapterContent == null ? chapterContentNull : chapterContent);
        List<Chapter> chapterPreNext = chapterService.getPreNextChIdByByBookIdAndChId(bookId,chId);
        Chapter chapterPre = null;
        Chapter chapterNext = null;
        for(int i = 0; i < chapterPreNext.size(); i++){
            if(i == 0 && !chapterPreNext.get(i).getChId().equals(chId)){
                chapterPre = chapterPreNext.get(i);
            } else if(i == chapterPreNext.size() - 1 && !chapterPreNext.get(i).getChId().equals(chId)){
                chapterNext = chapterPreNext.get(i);
            }
        }
        Map<String, Object> other = new HashMap();
        other.put("preChId", 0);
        other.put("preChCharge", 0);
        other.put("nextChId", 0);
        other.put("nextChCharge", 0);
        if(chapterPre != null){
            other.put("preChId", chapterPre.getChId());
            other.put("preChCharge", chapterPre.getChCharge());
        }
        if(chapterNext != null){
            other.put("nextChId", chapterNext.getChId());
            other.put("nextChCharge", chapterNext.getChCharge());
        }
        other.put("bookId", bookId);
        root.put("Other", other);
        return ResultUtil.getResultBySuccess(root);

    }
}
